from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.contrib import auth
from django.db.models import F
from django.db import transaction
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from bs4 import BeautifulSoup
import json

from blog import models
from blog.utils.validCode import get_valid_code_img
from blog.MyForm import UserForm
from blog.models import UserInfo


# 登录方法
def login(request):
    if request.method == "POST":
        response = {"user": None, "msg": None}
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        valid_code = request.POST.get('valid_code')
        valid_code_str = request.session.get("valid_code_str")
        if valid_code.upper() == valid_code_str.upper():
            user = auth.authenticate(username=user, password=pwd)
            if user:
                auth.login(request, user)
                response["user"] = user.username
            else:
                response["msg"] = "账号或密码错误！"

        else:
            response["msg"] = "验证码错误"

        return JsonResponse(response)
    return render(request, "login.html")


# 获取验证码
def get_validCode_img(request):
    data = get_valid_code_img(request)
    return HttpResponse(data)


# 主页
def index(request):
    article_list = models.Article.objects.all()
    # paginator = Paginator(article_list, 20)  # 每页显示20条
    # page_number = 3  # 示例页码，实际中从请求中获取
    # article_list = paginator.get_page(page_number)
    return render(request, "index.html", {"article_list": article_list})


# 注销
def logout(request):
    auth.logout(request)  # 等同于request.session.flush()
    return redirect("/login/")


# 注册方法
def register(request):
    if request.headers.get('x-requested-with') == 'XMLHttpRequest':
        form = UserForm(request.POST)
        response = {"user": None, "msg": None}
        if form.is_valid():
            response["user"] = form.cleaned_data.get("user")
            # 生成一条用户记录
            user = form.cleaned_data.get("user")
            pwd = form.cleaned_data.get("pwd")
            email = form.cleaned_data.get("email")
            avatar_obj = request.FILES.get("avatar")
            extra = {}
            if avatar_obj:
                extra['avatar'] = avatar_obj
            UserInfo.objects.create_user(username=user, password=pwd, email=email, **extra)
        else:
            response["msg"] = form.errors
        return JsonResponse(response)

    form = UserForm()
    return render(request, "register.html", {'form': form})

def not_found(request):
    return render(request, "not_found.html")

# 个人站点视图函数
def home_site(request, username, **kwargs):
    user = UserInfo.objects.filter(username=username).first()
    # 查询当前站点对象
    blog = user.blog
    # 判断用户是否存在
    if not user:
        # return render(request, "not_found.html")
        return redirect(not_found)

    # 取出当前用户对应的文章
    article_list = models.Article.objects.filter(user=user)
    if kwargs:
        condition = kwargs.get("condition")
        param = kwargs.get("param")
        if condition == "category":
            article_list = article_list.filter(category__title=param)
        elif condition == "tag":
            article_list = article_list.filter(tags__title=param)
        else:
            year, month = param.split("-")
            article_list = article_list.filter(create_time__year=year, create_time__month=month)

    return render(request, "home_site.html",
                  {"article_list": article_list, "username": username, 'blog': blog})



def article_detail(request, username, article_id):
    user = UserInfo.objects.filter(username=username).first()
    blog = user.blog
    article_obj = models.Article.objects.filter(user=user).filter(pk=article_id).first()

    comment_list = models.Comment.objects.filter(article_id=article_id)
    return render(request, "article_detail.html", locals())


# 点赞视图函数
@login_required
def digg(request):
    article_id = request.POST.get("article_id")
    is_up = json.loads(request.POST.get("is_up"))  # js传过来的是字符串，而不是布尔类型。点赞或反对
    user_id = request.user.pk

    obj = models.ArticleUpDown.objects.filter(user_id=user_id, article_id=article_id).first()
    response = {"state": True}
    if not obj:
        ard = models.ArticleUpDown.objects.create(user_id=user_id, article_id=article_id, is_up=is_up)
        queryset = models.Article.objects.filter(pk=article_id)
        if is_up:
            queryset.update(up_count=F("up_count") + 1)
        else:
            queryset.update(down_count=F("down_count") + 1)
    else:
        response['state'] = False
        response["handled"] = obj.is_up

    return JsonResponse(response)

@login_required
def comment(request):
    article_id = request.POST.get("article_id")
    pid = request.POST.get("pid")
    content = request.POST.get("content")
    user_id = request.user.pk

    with transaction.atomic():
        comment_obj = models.Comment.objects.create(user_id=user_id, article_id=article_id, content=content,
                                                    parent_comment_id=pid)
        models.Article.objects.filter(pk=article_id).update(comment_count=F("comment_count")+1)

    response = {}
    response["create_time"] = comment_obj.create_time.strftime("%Y-%m-%d %S")
    response["username"] = request.user.username
    response["content"] = content

    return JsonResponse(response)

@login_required
def get_comment_tree(request):
    article_id = request.GET.get("article_id")
    ret = list(models.Comment.objects.filter(article_id=article_id).order_by("pk").values("pk", "content",
                                                                                          "parent_comment_id"))

    return JsonResponse(ret, safe=False)


@login_required
def cn_backend(request):
    article_list = models.Article.objects.filter(user=request.user)

    return render(request, "backend/backend.html", locals())


@login_required
def add_article(request):
    if request.method == "POST":
        title = request.POST.get("title")
        content = request.POST.get("content")
        soup = BeautifulSoup(content, "html.parser")
        # 过滤标签
        for tag in soup.find_all():
            if tag.name == "script":
                tag.decompose()
        desc = soup.text[0:150]
        models.Article.objects.create(title=title, desc=desc, content=str(soup), user=request.user)
        return redirect("/blog/cn_backend/")
    return render(request, "backend/add_article.html")


@login_required
def edit_article(request, article_id):
    article_obj = models.Article.objects.filter(pk=article_id)
    article_title = article_obj.values("title")
    article_content = article_obj.values("content")
    # print(article_title, article_content)
    # return HttpResponse("ok")
    return render(request, "backend/edit_article.html", locals())


@login_required
def del_article(request, article_id):
    models.Article.objects.filter(pk=article_id).delete()
    return redirect(cn_backend)


